package oppty_status

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
	"time"
)

type GfyxOpptyStatusRepos struct {
	tenant_db.TenantDB
}

func NewOpptyStatusRepos() GfyxOpptyStatusReposIface {
	return &GfyxOpptyStatusRepos{}
}

func (g *GfyxOpptyStatusRepos) SaveOpptyStatus(ctx context.Context, data *GfyxOpptyStatus) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Create(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxOpptyStatusRepos) GetOpptyStatus(ctx context.Context, dataSource string, dataSourceId string, userGUID string) (*GfyxOpptyStatus, error) {
	gfyxOpptyStatus := &GfyxOpptyStatus{}
	err := g.GetTenantDB(ctx).
		Where("data_source = ?", dataSource).
		Where("data_source_id = ?", dataSourceId).
		Where("user_guid = ?", userGUID).
		Order("created_on desc").First(gfyxOpptyStatus).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return gfyxOpptyStatus, err
	}
	return gfyxOpptyStatus, nil
}

func (g *GfyxOpptyStatusRepos) GetOpptyStatusBatch(ctx context.Context, dataSource string, idList []string, userGUID string) ([]*GfyxOpptyStatus, error) {
	gfyxOpptyStatus := make([]*GfyxOpptyStatus, 0)
	if len(idList) == 0 {
		return gfyxOpptyStatus, nil
	}

	db := g.GetTenantDB(ctx).
		Where("data_source_id in (?)", idList).
		Where("user_guid =?", userGUID).
		Order("created_on desc")
	if dataSource == constants.OpptySourceRadarProject { //线索雷达项目页面
		db = db.Where("data_source in ('SALE','BUILDING','LAND')")
	} else if dataSource == constants.OpptySourceBidMerge {
		db = db.Where("data_source in ('PURCHASE','WINBID')")
	} else {
		db = db.Where("data_source = ?", dataSource)
	}
	err := db.Find(&gfyxOpptyStatus).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return gfyxOpptyStatus, nil
		}
		return nil, err
	}

	return gfyxOpptyStatus, nil
}

func (g *GfyxOpptyStatusRepos) UpdateStatus(ctx context.Context, dataSource string, dataSourceId string, userGUID string, status int32) (bool, error) {
	err := g.GetTenantDB(ctx).
		Table(GfyxOpptyStatus{}.TableName()).
		Where("data_source=?", dataSource).
		Where("data_source_id=?", dataSourceId).
		Where("user_guid=?", userGUID).
		Updates(map[string]interface{}{"status": status}).Error
	if err != nil {
		return false, err
	}
	return true, nil

}

func (g *GfyxOpptyStatusRepos) GetCurrentMonthViewCount(ctx context.Context, userGUID string, monthStart string, monthEnd string) (int64, error) {
	var total int64
	err := g.GetTenantDB(ctx).Table(GfyxOpptyStatus{}.TableName()).Where("user_guid = ? and created_on >= ? and created_on < ? and is_deleted = ?",
		userGUID, monthStart, monthEnd, constants.IsDeletedFalse).Count(&total).Error
	if err != nil {
		return 0, err
	}
	return total, nil
}
